import CountSelection from "@/components/selectionBox/countSelection";
import SelectionBox from "@/components/selectionBox/SelectionBox";
import { useAppSelector } from "@/store";
import { changeAddToCarList } from "@/store/modules/coffeeOrder";

import {
  changeShowCoffeeSelection,
  changeSizeSelection,
  changeIceSelection,
  changeSugerSelection,
  changeCoffeeCountSelection,
} from "@/store/modules/coffeeSelection";

import { coffeeSelectionType, coffeeType, orderType } from "@/type/coffeeType";

import { Modal } from "antd";

import React, { FC, memo, ReactNode } from "react";
import { useDispatch } from "react-redux";
import { CoffeeSelectionWrapper } from "./style";

interface IProps {
  children?: ReactNode;
  coffee: coffeeType;
  coffeeSelect: coffeeSelectionType;
}

const CoffeeSelection: FC<IProps> = memo((props) => {
  const { coffee, coffeeSelect } = props;

  // 拿到咖啡选项、订单的store
  const { select, order } = useAppSelector((state) => ({
    select: state.coffeeSelection,
    order: state.coffeeOrder,
  }));

  const dispatch = useDispatch();

  /**
   * 关闭选择遮罩时都把store里的选中重置
   */
  const resetSelectionStore = () => {
    dispatch(changeCoffeeCountSelection(0));
    dispatch(changeSizeSelection("middle"));
    dispatch(changeIceSelection("ice"));
    dispatch(changeSugerSelection("normalSuger"));
  };

  const handleOk = () => {
    // 关闭遮罩
    dispatch(changeShowCoffeeSelection(false));
    // 重置咖啡选项
    resetSelectionStore();

    // 将参数添加到order的store中
    const copySelect = { ...select };
    delete copySelect.showCoffeeSelection;
    const newOrder: orderType = { ...coffee, ...copySelect };

    dispatch(changeAddToCarList(newOrder));
  };

  const handleCancel = () => {
    dispatch(changeShowCoffeeSelection(false));
    resetSelectionStore();
  };

  return (
    <CoffeeSelectionWrapper>
      <div>
        <Modal
          className="modal"
          open={coffeeSelect.showCoffeeSelection}
          onOk={handleOk}
          onCancel={handleCancel}
          okText="下单"
          cancelText="取消"
        >
          <h1>
            『{coffee?.name}』
            <span style={{ fontSize: "16px" }}>单价￥{coffee?.price}</span>
          </h1>
          <CountSelection count={select.count} />
          <SelectionBox item={"size"} />
          <SelectionBox item={"ice"} />
          <SelectionBox item={"suger"} />
        </Modal>
      </div>
    </CoffeeSelectionWrapper>
  );
});

export default CoffeeSelection;
